/* 请求体配置 */
import axios from 'axios';
import { Toast } from 'antd-mobile';
import { history } from 'umi';

export default function Request(options = {}) {
  const URL_TOKEN =
    options.url +
    '?token=' +
    (sessionStorage.getItem('token') ? sessionStorage.getItem('token') : '');
  const URL_NOT_TOKEN = options.url;
  const ADDRESS_TOKEN =
    process.env.NODE_ENV === 'development' ? '/api' + URL_TOKEN : URL_TOKEN;
  const ADDRESS_NOT_TOKEN =
    process.env.NODE_ENV === 'development'
      ? '/api' + URL_NOT_TOKEN
      : URL_NOT_TOKEN;
  /* 请求头 */
  const headers = {
    'Content-Type': options.isForm ? 'multipart/form-data' : 'application/json',
  };
  const httpRequestBody = {
    headers: headers,
    method: options.method || 'GET',
    url: options.isToken ? ADDRESS_TOKEN : ADDRESS_NOT_TOKEN,
    withCredentials: true,
    timeout: 1800000,
  };

  if (
    Object.is(httpRequestBody.method, 'POST') ||
    Object.is(httpRequestBody.method, 'PUT')
  ) {
    httpRequestBody.data = options.data || '';
  } else {
    httpRequestBody.params = options.data || '';
  }
  return axios(httpRequestBody).then(
    res => {
      const { code, msg } = res.data;
      if (code && code !== 200 && code !== 0) {
        Toast.info(msg, 1);
      }
      if ((code && code === 1001) || code === 1002) {
        Toast.info('token过期请重新登录', 1);
        history.push('/login');
      }
      return res.data;
    },
    () => {
      Toast.info('服务器繁忙，请稍后重试~', 1);
    },
  );
}
